package com.cyw.common.config.jackson.deserializer;

import com.cyw.common.utils.DateUtils;
import com.cyw.common.utils.RegexUtils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * LocalDateTime反序列化
 * @author cyw
 * @date 2021-03-31
 */
public class StringOrTimestamp2LocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {

   private static final long serialVersionUID = 1360523766414381307L;

   public StringOrTimestamp2LocalDateTimeDeserializer() {
      this(null);
   }

   public StringOrTimestamp2LocalDateTimeDeserializer(Class<LocalDateTime> vc) {
      super(vc);
   }


   @Override
   public LocalDateTime deserialize(JsonParser p, DeserializationContext context) throws IOException {
      String time = StringUtils.trim(p.getText());

      return RegexUtils.isTimeStampMilli(time) ?
              DateUtils.timestamp2LocalDateTime(p.getValueAsLong()) :
              DateUtils.parseLocalDateTime(time);
   }
}